# PROJECT_NAME: vehicle_detection
# NAME: API_test01_detailed
# Author: XMX
# Date: 2025/11/11
import requests
import time
import json
from datetime import datetime


class TrafficMonitor:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url

    def analyze_and_monitor(self, video_path, conf_threshold=0.25):
        """分析视频并实时监控"""
        try:
            print("上传视频文件中...")
            with open(video_path, 'rb') as f:
                files = {'file': f}
                data = {'conf_threshold': conf_threshold}

                response = requests.post(f"{self.base_url}/api/analyze/video", files=files, data=data)
                result = response.json()

            if not result['success']:
                print("任务创建失败")
                return

            task_id = result['task_id']
            print(f"任务创建成功: {task_id}")

            self._monitor_task(task_id)

        except Exception as e:
            print(f"错误: {e}")

    def _monitor_task(self, task_id):
        """监控任务进度"""
        print(f"开始监控任务进度...")
        print("=" * 60)

        start_time = time.time()
        last_stats_time = 0

        while True:
            try:
                current_time = time.time()
                elapsed = current_time - start_time

                # 获取任务状态
                status_response = requests.get(f"{self.base_url}/api/tasks/{task_id}")
                if status_response.status_code != 200:
                    print("无法获取任务状态")
                    break

                status_data = status_response.json()
                current_status = status_data['status']

                print(f"运行时间: {elapsed:.1f}s | 状态: {current_status}")

                # 每秒获取一次实时统计
                if current_time - last_stats_time >= 1.0:
                    stats_response = requests.get(f"{self.base_url}/api/realtime/stats")
                    if stats_response.status_code == 200:
                        stats = stats_response.json()
                        if stats['vehicle_count'] > 0:
                            print(f"实时统计 - 车辆: {stats['vehicle_count']} | 告警: {stats['active_alerts']}")
                    last_stats_time = current_time

                # 检查任务完成状态
                if current_status == 'completed':
                    print(f"任务完成! 总耗时: {elapsed:.1f}秒")
                    self._handle_completion(task_id, status_data)
                    break
                elif current_status == 'failed':
                    print(f"任务失败: {status_data.get('error', '未知错误')}")
                    break

            except Exception as e:
                print(f"监控错误: {e}")
                break

            time.sleep(1)

    def _handle_completion(self, task_id, status_data):
        """处理任务完成"""
        try:
            print("下载处理后的视频...")
            download_url = f"{self.base_url}/api/video/output/{task_id}"
            response = requests.get(download_url, stream=True)

            if response.status_code == 200:
                output_filename = f"processed_{task_id}.mp4"
                total_size = 0

                with open(output_filename, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)
                            total_size += len(chunk)
                            print(f"下载进度: {total_size / (1024 * 1024):.1f}MB", end="\r")

                print(f"视频已保存: {output_filename}")

                self._show_final_stats()

            else:
                print("视频下载失败")

        except Exception as e:
            print(f"下载错误: {e}")

    def _show_final_stats(self):
        """显示最终统计信息"""
        try:
            stats_response = requests.get(f"{self.base_url}/api/realtime/stats")
            if stats_response.status_code == 200:
                stats = stats_response.json()
                print("\n" + "=" * 50)
                print("最终分析报告")
                print("=" * 50)
                print(f"时间: {stats['timestamp']}")
                print(f"检测到车辆总数: {stats['vehicle_count']}")
                print(f"确认告警数量: {stats['active_alerts']}")

                if stats['vehicle_distribution']:
                    print("车辆类型分布:")
                    for vehicle_type, count in stats['vehicle_distribution'].items():
                        print(f"  {vehicle_type}: {count}")

                if stats['alert_details']:
                    print("告警详情:")
                    for alert in stats['alert_details']:
                        print(f"  - {alert['type']} (置信度: {alert['confidence']:.2f})")

        except Exception as e:
            print(f"获取统计信息失败: {e}")


def main():
    monitor = TrafficMonitor()
    video_path = r"F:\MyProject\Python\vehicle_detection\datasets\textVideos\test_video.mp4"

    print("智慧交通沙盘检测系统")
    print("=" * 40)
    monitor.analyze_and_monitor(video_path, conf_threshold=0.25)


if __name__ == "__main__":
    main()